<?php

namespace app\pay\controller;

use app\api\logic\Vip;
use app\common\exception\BusinessException;
use app\common\model\User;
use app\common\model\UserVip;
use app\common\service\UserService;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use think\facade\Cache;
use think\Response;
use v8_pay\AlipayNotify;
use v8_pay\AlipaySubmit;

class Order extends Base
{
    /**
     * 显示支付地址
     * @throws
     */
    public function showPayUrl(): Response
    {
        // 请求参数
        $url = $this->request->param('url', '');
        if (!$url)
        {
            throw new BusinessException('二维码地址不得为空');
        }

        // 生成二维码
        $qrCode = new QrCode();
        $qrCode->setSize(300);
        $qrCode->setMargin(10);
        $qrCode->setEncoding('UTF-8');
        $qrCode->setText($url);
        $qrCode->setRoundBlockSize(true);
        $qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);

        // 返回
        return Response::create($qrCode->writeString())->code(200)->header(['Content-Type' => 'image/png']);
    }

    /**
     * 创建订单
     * @throws BusinessException
     */
    public function submit()
    {
        // 请求参数
        $uid = $this->request->param('uid', 0); // 用户UID
        $type = $this->request->param('type', 0); // 支付类型:1.充值积分 2.充值会员
        $extend = $this->request->param('extend', 0); //扩展字段

        // 检查参数
        if (!$uid)
        {
            throw new BusinessException('用户信息不得为空');
        }
        if (!$type)
        {
            throw new BusinessException('支付类型不得为空');
        }
        if ($type == 2 && !$extend)
        {
            throw new BusinessException('扩展数据不得为空');
        }

        // 查询用户信息
        $nickName = (new User())->where(['id' => $uid])->value('nickname', '');

        // 获取支付参数
        $alipay_config = getPayConfig();

        // 组装订单参数
        $orderNo = 'S' . date('YmdHis') . rand(1000, 9999);

        // 保存订单号和Uid
        $key = 'pay_order_' . $orderNo;
        if (!Cache::set($key, [
            'order_no' => $orderNo,
            'order_uid' => $uid,
            'order_type' => $type,
            'order_extend' => $extend,
        ], 86400 * 3))
        {
            throw new BusinessException('保存订单关系失败');
        }

        // 生成支付标题和金额
        if ($type == 1)
        {
            $title = "用户Id{$uid}-翰林小程序充值";
            $money = 10;
        }
        else
        {
            $price_list = Vip::PRICE_LIST;
            $price_list = array_dict($price_list, 'id');
            //$title = "用户{$nickName}-小程序充值" . $price_list[$extend]['name'];
            $title = "用户Id{$uid}-翰林小程序充值";
            $money = $price_list[$extend]['price'];
        }

        // 构建表单
        $parameter = [
            "pid" => $alipay_config['partner'],
            "notify_url" => 'https://learn.gaojiufeng.cn/pay/order/notify',
            "return_url" => 'https://h5.gaojiufeng.cn/#/pages/user/vip/payRes',
            "out_trade_no" => $orderNo,
            "name" => $title,
            "money" => $money,
            "sitename" => '微信小程序-翰林刷题'
        ];

        // 返回
        $alipaySubmit = new AlipaySubmit($alipay_config);
        return $alipaySubmit->buildRequestForm($parameter);
    }

    /**
     * notify
     * @throws BusinessException
     */
    public function notify()
    {
        // 请求参数
        $param = $this->request->param();

        // 获取支付参数
        $alipay_config = getPayConfig();

        // 验证签名
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if ($verify_result)
        {
            // 提取商户单号
            $out_trade_no = $param['out_trade_no'];

            // 查询订单号关联Uid
            $key = 'pay_order_' . $out_trade_no;
            $orderInfo = Cache::get($key);
            if (!$orderInfo)
            {
                return "fail";
            }

            // 提取用户UID
            $order_uid = $orderInfo['order_uid'];

            // 提取充值类型:1.充值积分 2.充值会员
            $order_type = $orderInfo['order_type'];
            if ($order_type == 1)
            {
                // 赠送积分
                $userService = new UserService();
                $userService->sendScoreToUid($order_uid, 10000, 9);
            }
            elseif ($order_type == 2)
            {
                // 查询用户信息
                $userInfo = (new User())->getUserInfo($order_uid);
                if (!$userInfo || !$userInfo['profession_id'])
                {
                    return "fail";
                }

                // 充值会员
                $order_extend = $orderInfo['order_extend'];
                $priceDict = array_dict(Vip::PRICE_LIST, 'id');
                if (empty($priceDict[$order_extend]))
                {
                    return "fail";
                }
                (new UserVip())->setExpire($order_uid, $userInfo['profession_id'], $priceDict[$order_extend]['expire']);

            }

            // 清除订单信息
            Cache::set($key, '', 0);

            return "success";
        }
        else
        {
            return "fail";
        }

    }
}
